home *** CD-ROM | disk | FTP | other *** search
/ Czech Logic, Card & Gambling Games / Logické hry.iso / hry / Robocode / robocode-setup-1.0.7.jar / extract.jar / robots / sample / TrackFire.java < prev    next >
Encoding:
Java Source  |  2005-02-18  |  1.7 KB  |  65 lines

  1. package sample;
  2. import robocode.*;
  3. /**
  4.  * TrackFire - a sample robot by Mathew Nelson
  5.  * 
  6.  * Sits still.  Tracks and fires at the nearest robot it sees
  7.  */
  8. public class TrackFire extends Robot
  9. {
  10.     /**
  11.      * TrackFire's run method
  12.      */
  13.     public void run() {
  14.         while (true)
  15.         {
  16.             turnGunRight(10); // Scans automatically
  17.         }
  18.     }
  19.     /**
  20.      * onScannedRobot:  We have a target.  Go get it.
  21.      */
  22.     public void onScannedRobot(ScannedRobotEvent e) {
  23.         // Calculate exact location of the robot
  24.         double absoluteBearing = getHeading() + e.getBearing();
  25.         double bearingFromGun = normalRelativeAngle(absoluteBearing - getGunHeading());
  26.         // If it's close enough, fire!
  27.         if (Math.abs(bearingFromGun) <= 3) {
  28.             turnGunRight(bearingFromGun);
  29.             // We check gun heat here, because calling fire() 
  30.             // uses a turn, which could cause us to lose track
  31.             // of the other robot.
  32.             if (getGunHeat() == 0)
  33.                 fire (Math.min(3 - Math.abs(bearingFromGun),getEnergy() - .1));
  34.         }
  35.         // otherwise just set the gun to turn.
  36.         // Note:  This will have no effect until we call scan()
  37.         else {
  38.             turnGunRight(bearingFromGun);
  39.         }
  40.         // Generates another scan event if we see a robot.
  41.         // We only need to call this if the gun (and therefore radar)
  42.         // are not turning.  Otherwise, scan is called automatically.
  43.         if (bearingFromGun == 0)
  44.             scan();
  45.     }
  46.     
  47.     public void onWin(WinEvent e)
  48.     {
  49.         //Victory dance    
  50.         turnRight(36000);
  51.     }
  52.     
  53.     // Helper function
  54.     public double normalRelativeAngle(double angle) {
  55.         if (angle > -180 && angle <= 180)
  56.             return angle;
  57.         double fixedAngle = angle;
  58.         while (fixedAngle <= -180)
  59.             fixedAngle += 360;
  60.         while (fixedAngle > 180)
  61.             fixedAngle -= 360;
  62.         return fixedAngle;
  63.     }
  64.  
  65. }